package com.agv.web.adm.cat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.json.JSONArray;
import org.json.JSONObject;

import com.agv.core.objectDomain.AdmCatalogo;
import com.agv.core.objectDomain.Catalogo;
import com.agv.core.objectDomain.InfoAuditoria;
import com.agv.core.objectDomain.ParamCatalogo;
import com.agv.core.objectDomain.Paso;
import com.agv.core.objectDomain.Usuario;
import com.agv.core.services.ICatalogosService;
import com.agv.core.util.Constantes;
import com.agv.core.util.Util;
import com.agv.web.MonitoringDispatchAction;

public class AdmCatDispatchAction extends MonitoringDispatchAction {

	private ICatalogosService catalogosService;

	@SuppressWarnings("unchecked")
	public ActionForward addParameters(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> params = (List<Map<String, String>>) request
				.getSession().getAttribute("paramsList");

		Map<String, String> map = new HashMap<String, String>();

		map.put("name", request.getParameter("field"));
		map.put("type", request.getParameter("dataType"));
		map.put("dataLenght", request.getParameter("lenght"));
		map.put("valtypes", request.getParameter("valType"));
		map.put("regexVal", request.getParameter("regexVal"));
		map.put("isId", request.getParameter("id"));
		map.put("isReq", request.getParameter("required"));
		map.put("isDupVal", request.getParameter("dupVal"));
		map.put("otTable", request.getParameter("otTable"));
		map.put("nbTable", request.getParameter("nbTable"));
		map.put("nbField", request.getParameter("nbField"));
		map.put("nbLegend", request.getParameter("nbLegend"));
		map.put("alias", request.getParameter("alias"));
		map.put("isAutoComplete", request.getParameter("nbAutoComplete"));

		if (params == null) {
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			list.add(map);
			request.getSession().setAttribute("paramsList", list);
		} else {
			for (Map<String, String> param : params) {
				if (param.containsValue(map.get("name"))) {
					out
							.print("{'success':false,'msg':'El parametro ya existe'}");
					return null;
				}
			}
			params.add(map);
			request.getSession().setAttribute("paramsList", params);
		}
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward addStep(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> steps = (List<Map<String, String>>) request
				.getSession().getAttribute("stepsList");

		Map<String, String> map = new HashMap<String, String>();

		map.put("name", request.getParameter("name"));
		map.put("isReq", request.getParameter("required"));

		if (steps == null) {
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			map.put("step", "1");
			list.add(map);
			request.getSession().setAttribute("stepsList", list);
		} else {
			for (Map<String, String> step : steps) {
				if (step.containsValue(map.get("name"))) {
					out
							.print("{'success':false,'msg':'El parametro ya existe'}");
					return null;
				}
			}
			map.put("step", "" + (steps.size() + 1));
			steps.add(map);
			request.getSession().setAttribute("stepsList", steps);
		}
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward deleteParameters(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> params = (List<Map<String, String>>) request
				.getSession().getAttribute("paramsList");

		List<Map<String, String>> paramsAux = new ArrayList<Map<String, String>>();

		Map<String, String> map = new HashMap<String, String>();
		map.put("name", request.getParameter("field"));

		for (Map<String, String> param : params) {
			if (!param.containsValue(map.get("name"))) {
				paramsAux.add(param);
			}
		}
		request.getSession().setAttribute("paramsList", paramsAux);
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward deleteSteps(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> params = (List<Map<String, String>>) request
				.getSession().getAttribute("stepsList");

		List<Map<String, String>> paramsAux = new ArrayList<Map<String, String>>();

		Map<String, String> map = new HashMap<String, String>();
		map.put("name", request.getParameter("name"));

		for (Map<String, String> param : params) {
			if (!param.containsValue(map.get("name"))) {
				paramsAux.add(param);
			}
		}
		request.getSession().setAttribute("stepsList", paramsAux);
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward addConfiguration(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> params = (List<Map<String, String>>) request
				.getSession().getAttribute("paramsList");

		Map<String, String> configuration = new HashMap<String, String>();

		configuration.put("title", request.getParameter("title"));
		configuration.put("schema", request.getParameter("schema"));
		configuration.put("table", request.getParameter("table"));
		configuration.put("sequence", request.getParameter("sequence"));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("confParams", configuration);
		map.put("catParams", params);

		catalogosService.addConfiguration(map);

		request.getSession().removeAttribute("paramsList");
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward addStepsConfiguration(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ServletOutputStream out = response.getOutputStream();
		List<Map<String, String>> params = (List<Map<String, String>>) request
				.getSession().getAttribute("stepsList");

		Map<String, String> configuration = new HashMap<String, String>();

		configuration.put("title", request.getParameter("title"));
		configuration.put("isAnidate", request.getParameter("isAnidate"));
		configuration.put("module", request.getParameter("module"));
		configuration.put("subModule", request.getParameter("subModule"));
		configuration.put("function", request.getParameter("func"));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("confParams", configuration);
		map.put("stepParams", params);

		catalogosService.addStepConfiguration(map);

		request.getSession().removeAttribute("paramsList");
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward getCatConfiguration(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ServletOutputStream out = response.getOutputStream();

		Integer idCat = new Integer(request.getParameter("idCat"));

		Map<String, String> mapConf = catalogosService
				.getCatConfiguration(idCat);

		JSONObject responseObj = new JSONObject();
		JSONObject data = new JSONObject();
		data.put("title", mapConf.get("nb_title"));
		data.put("isAnidate", mapConf.get("is_anidate"));
		data.put("seqConf", mapConf.get("seq_conf"));

		JSONObject steps = new JSONObject();

		String[] a = mapConf.get("seq_conf").split(",");
		String[] idCats = new String[a.length];

		int count = 0;
		for (String p : a) {
			idCats[count++] = p.substring(0, p.length() - 1);
		}

		List<Map<String, String>> mapSteps = catalogosService
				.getCatSteps(idCats);

		JSONArray array = new JSONArray();
		for (Map<String, String> step : mapSteps) {
			JSONObject object = new JSONObject();
			object.put("id_catalogo", step.get("id_catalogo"));
			object.put("nb_catalogo", step.get("nb_catalogo"));
			object.put("nb_tabla", step.get("nb_tabla"));
			object.put("nb_campoautocompletar", step
					.get("nb_campoautocompletar"));
			object.put("nb_campoid", step.get("nb_campoid"));
			object.put("nb_secuencia", step.get("nb_secuencia"));
			object.put("tp_borrado", step.get("tp_borrado"));
			array.put(object);
		}

		responseObj.put("data", data);
		responseObj.put("steps", array);
		responseObj.put("success", true);

		out.print(responseObj.toString());
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward getParameters(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ServletOutputStream out = response.getOutputStream();

		List<HashMap<String, String>> params = (List<HashMap<String, String>>) request
				.getSession().getAttribute("paramsList");

		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();

		if (params != null) {
			for (Map<String, String> param : params) {
				JSONObject json = new JSONObject();
				json.put("name", param.get("name"));
				json.put("type", param.get("type"));
				array.put(json);
			}
		}
		object.put("data", array);
		out.println(object.toString());
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward getSteps(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ServletOutputStream out = response.getOutputStream();

		List<HashMap<String, String>> params = (List<HashMap<String, String>>) request
				.getSession().getAttribute("stepsList");

		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();

		if (params != null) {
			for (Map<String, String> param : params) {
				JSONObject json = new JSONObject();
				json.put("name", param.get("name"));
				json.put("step", param.get("step"));
				json.put("isReq", param.get("isReq"));
				array.put(json);
			}
		}
		object.put("data", array);
		out.println(object.toString());
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward cleanParameters(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ServletOutputStream out = response.getOutputStream();
		request.getSession().removeAttribute("paramsList");
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward cleanSteps(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ServletOutputStream out = response.getOutputStream();
		request.getSession().removeAttribute("stepsList");
		out.print("{'success':true}");
		return null;
	}

	@SuppressWarnings("unchecked")
	public ActionForward getCombo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			ServletOutputStream out = response.getOutputStream();
			String tpCombo = request.getParameter("tpCombo");
			JSONArray array = new JSONArray();
			JSONObject object = new JSONObject();

			if (tpCombo.equals("schemas")) {
				List<Map<String, String>> tables = (List<Map<String, String>>) catalogosService
						.getCombo("select distinct schemaname as id, schemaname as name "
								+ " from pg_stat_user_tables where schemaname <> 'public'");

				for (Map<String, String> table : tables) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("tables")) {
				String nbSchema = request.getParameter("schema");
				List<Map<String, String>> tables = (List<Map<String, String>>) catalogosService
						.getCombo("select relname as id, relname as name from pg_stat_user_tables where schemaname = '"
								+ nbSchema
								+ "' "
								+ " and '"
								+ nbSchema
								+ ".' || relname not in (select nb_tabla from adm.adm001_cfg_catalogos)");

				for (Map<String, String> table : tables) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("sequences")) {
				String nbTable = request.getParameter("table");
				List<Map<String, String>> tables = (List<Map<String, String>>) catalogosService
						.getCombo("SELECT c.relname as id,  c.relname as name FROM pg_class c WHERE c.relkind = 'S' and c.relname like '"
								+ nbTable + "%'");

				for (Map<String, String> table : tables) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("fields")) {
				String addParam = request.getParameter("addParam");
				String nbTable = request.getParameter("table");
				List<Map<String, String>> tables = (List<Map<String, String>>) catalogosService
						.getCombo("SELECT column_name as id,column_name as name,data_type as type, character_maximum_length as lenght "
								+ " FROM information_schema.columns WHERE table_name = "
								+ "'" + nbTable + "' order by ordinal_position");
				List<Map<String, String>> fields = new ArrayList<Map<String, String>>();

				if (addParam != null) {
					List<Map<String, String>> params = (List<Map<String, String>>) request
							.getSession().getAttribute("paramsList");
					boolean enc = false;
					Map<String, String> temp = null;
					for (Map<String, String> field : tables) {
						enc = false;
						for (Map<String, String> param : params) {
							temp = field;
							if (param.get("name").equals(field.get("id"))) {
								enc = true;
								break;
							}
						}
						if (!enc) {
							fields.add(temp);
						}
					}

					for (Map<String, String> table : fields) {
						JSONObject json = new JSONObject();
						json.put("type", table.get("type"));
						json.put("lenght", table.get("lenght"));
						json.put("id", table.get("id"));
						json.put("name", table.get("name"));
						array.put(json);
					}
				} else {
					for (Map<String, String> table : tables) {
						JSONObject json = new JSONObject();
						json.put("type", table.get("type"));
						json.put("lenght", table.get("lenght"));
						json.put("id", table.get("id"));
						json.put("name", table.get("name"));
						array.put(json);
					}
				}
			} else if (tpCombo.equals("vtypes")) {
				JSONObject json = new JSONObject();
				json.put("id", "alfa");
				json.put("name", "alfa");
				array.put(json);

				json = new JSONObject();
				json.put("id", "alfanum");
				json.put("name", "alfanum");
				array.put(json);

				json = new JSONObject();
				json.put("id", "email");
				json.put("name", "email");
				array.put(json);
			} else if (tpCombo.equals("modules")) {
				List<Map<String, String>> objects = (List<Map<String, String>>) catalogosService
						.getCombo("select id_modulo as id, nb_modulo as name from empresa.emp012_modulo");
				for (Map<String, String> table : objects) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("subModules")) {
				String idModule = request.getParameter("module");
				List<Map<String, String>> objects = (List<Map<String, String>>) catalogosService
						.getCombo("select id_submodulo as id, nb_submodulo as name from empresa.emp013_submodulo where id_modulo = "
								+ idModule);
				for (Map<String, String> table : objects) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("functions")) {
				String idModule = request.getParameter("module");
				String idSubmodule = request.getParameter("subModule");
				List<Map<String, String>> objects = (List<Map<String, String>>) catalogosService
						.getCombo("select id_funcion as id, nb_funcion as name from empresa.emp010_funcion where id_modulo = "
								+ idModule
								+ " and id_submodulo = "
								+ idSubmodule);
				for (Map<String, String> table : objects) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			} else if (tpCombo.equals("catalogs")) {
				List<Map<String, String>> objects = (List<Map<String, String>>) catalogosService
						.getCombo("select id_catalogo as id, id_catalogo || ' - ' || nb_catalogo as name from adm.adm001_cfg_catalogos ");
				for (Map<String, String> table : objects) {
					JSONObject json = new JSONObject();
					json.put("id", table.get("id"));
					json.put("name", table.get("name"));
					array.put(json);
				}
			}

			object.put("data", array);
			out.println(object.toString());
			return null;
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward irInicio(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			request.getSession().setAttribute("pasoActual", String.valueOf(1));
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward irAtras(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			HttpSession session = request.getSession();
			session.removeAttribute("catCompleto");

			Integer secuenciaActual = Integer.parseInt((String) request
					.getSession().getAttribute("pasoActual"));
			if (secuenciaActual > 1) {
				secuenciaActual = secuenciaActual - 1;
			}
			session.setAttribute("pasoActual", String.valueOf(secuenciaActual));
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward irAdelante(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();
			session.removeAttribute("catCompleto");

			AdmCatForm admCatForm = (AdmCatForm) form;
			Integer secuenciaActual = Integer.parseInt((String) request
					.getSession().getAttribute("pasoActual"));

			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Paso pasoActual = admCatalogo.getPasos().get(secuenciaActual - 1);

			if (pasoActual.getStEstatus().equals(Constantes.COMPLETADO)) {
				Integer totalPasos = (Integer) request.getSession()
						.getAttribute("totalPasos");

				if (secuenciaActual < totalPasos) {
					secuenciaActual = secuenciaActual + 1;
				} else {
					session.setAttribute("catCompleto", "si");
				}
				request.getSession().setAttribute("pasoActual",
						String.valueOf(secuenciaActual));
			} else {
				ActionMessages messages = new ActionMessages();
				ActionMessage msg = new ActionMessage(
						"agv.adm.cat.pasoNoCompletado", secuenciaActual);
				messages.add("message", msg);
				saveMessages(request, messages);
			}

			Integer indice = Integer.parseInt((String) session
					.getAttribute("pasoActual")) - 1;
			Catalogo catalogo = admCatalogo.getCatalogos().get(indice);

			int cont = 0;
			for (String value : admCatForm.getNbPropiedades()) {
				if (!value.equals("")) {
					catalogo.getParams().get(cont).setVlValue(
							admCatForm.getNbPropiedades()[cont]);
				}
				cont++;
			}

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward agregar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			HttpSession session = request.getSession();
			AdmCatForm admCatForm = (AdmCatForm) form;
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");

			Integer indice = Integer.parseInt((String) session
					.getAttribute("pasoActual")) - 1;
			Catalogo catalogo = admCatalogo.getCatalogos().get(indice);
			String nbTabla = catalogo.getNbTabla();
			ArrayList<String> nbCamposDuplicidad = catalogo
					.getNbCamposDuplicidad();

			ActionMessages messages = new ActionMessages();

			int cont = 0;
			for (String value : admCatForm.getNbPropiedades()) {
				if (value.equals("")) {
					ActionMessage msg = new ActionMessage(
							"agv.adm.cat.campoRequerido");
					messages.add("message", msg);
					saveMessages(request, messages);
					admCatForm.getNbPropiedades()[cont] = null;
					return mapping.findForward("cfgCatalogos");
				} else {

					boolean resValidacion = false;
					String tpValidacion = catalogo.getParams().get(cont)
							.getTpValidacion();
					String nbCampo = catalogo.getParams().get(cont)
							.getNbCampoTabla();

					if (tpValidacion != null) {
						if (tpValidacion.equals(Constantes.VALIDACION_ALFA)) {
							resValidacion = Util.validarAlfa(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_ALFA_NUM)) {
							resValidacion = Util.validarAlfaNumerico(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_CORREO)) {
							resValidacion = Util.validarCorreo(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_NUM)) {
							resValidacion = Util.validarNumerico(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_FECHA)) {
							resValidacion = true;
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_DECIMAL)) {
							resValidacion = true;
						}

						catalogo.getParams().get(cont).setVlValue(
								admCatForm.getNbPropiedades()[cont]);

						if (!resValidacion) {
							messages = new ActionMessages();
							ActionMessage msg = new ActionMessage(
									"agv.adm.cat.formato", catalogo.getParams()
											.get(cont).getNbLeyenda());
							messages.add("message", msg);
							saveMessages(request, messages);
						}

						if (nbCamposDuplicidad.contains(nbCampo)
								&& session.getAttribute("actualizarCatalogo") == null) {
							boolean res = catalogosService.validaDuplicidad(
									nbCampo, value, nbTabla);
							if (res) {
								messages = new ActionMessages();
								ActionMessage msg = new ActionMessage(
										"agv.adm.cat.duplicidad", catalogo
												.getParams().get(cont)
												.getNbLeyenda());
								messages.add("message", msg);
								saveMessages(request, messages);
							}
						}

					} else {
						catalogo.getParams().get(cont).setVlValue(
								admCatForm.getNbPropiedades()[cont]);
					}
				}
				cont++;
			}

			if (!messages.isEmpty()) {
				return mapping.findForward("cfgCatalogos");
			}

			admCatalogo.getPasos().get(indice).setStEstatus(
					Constantes.COMPLETADO);
			request.getSession().setAttribute("pasoActual",
					String.valueOf(indice + 2));
			if ((indice + 1) == admCatalogo.getPasos().size()) {
				request.getSession().setAttribute("catCompleto", "si");
			}
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}

	}

	public ActionForward insertarCatBd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();
			session.setAttribute("catInsertado", "si");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.insertarCatalgoBD(admCatalogo, usuario
					.getIdUsuario());
			admCatalogo.setStEstatus(Constantes.COMPLETADO);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward borrar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();

			Integer index = Integer.parseInt(request.getParameter("index")) - 1;
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbCampoId = catalogo.getNbCampoId();
			Integer vlValorId = Integer.parseInt(reg.get(nbCampoId));

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.borrarCatalgoBD(admCatalogo, usuario
					.getIdUsuario(), vlValorId, catalogo.getNbCampoEstatus());

			session.setAttribute("catBorrado", "si");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward actualizar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			request.getSession().removeAttribute("buscaCatalogo");
			request.getSession().setAttribute("altaCatalogo", "si");
			request.getSession().setAttribute("actualizarCatalogo", "si");
			Integer index = Integer.parseInt(request.getParameter("index")) - 1;

			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			for (ParamCatalogo paramCatalogo : catalogo.getParams()) {
				paramCatalogo.setVlValue(reg.get(
						paramCatalogo.getNbCampoTabla()).trim());
			}

			request.getSession().setAttribute("index", index);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward actualizarCatBd(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			HttpSession session = request.getSession();

			Integer index = (Integer) request.getSession()
					.getAttribute("index");
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbCampoId = catalogo.getNbCampoId();
			Integer vlValorId = Integer.parseInt(reg.get(nbCampoId));

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.actualizarCatalgoBD(admCatalogo, usuario
					.getIdUsuario(), vlValorId);
			admCatalogo.setStEstatus(Constantes.COMPLETADO);

			session.setAttribute("catInsertado", "si");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward buscar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			String vlValor = request.getParameter("paramBusquedaCat");
			request.getSession().setAttribute("paramBusquedaCat", vlValor);

			request.getSession().setAttribute("buscaCatalogo", "si");
			request.getSession().removeAttribute("altaCatalogo");
			request.getSession().removeAttribute("actualizarCatalogo");
			request.getSession().removeAttribute("catInsertado");
			request.getSession().removeAttribute("catCompleto");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward consultaInfoAuditoria(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			Integer index = Integer.parseInt(request.getParameter("index")) - 1;
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbTabla = catalogo.getNbTabla();
			String nbCampoId = catalogo.getNbCampoId();
			String vlValorId = reg.get(nbCampoId);

			InfoAuditoria infoAuditoria = catalogosService
					.consultaInfoAuditoria(nbTabla, nbCampoId, vlValorId);
			request.setAttribute("infoAuditoriaObj", infoAuditoria);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public void setCatalogosService(ICatalogosService catalogosService) {
		this.catalogosService = catalogosService;
	}

}
